<?php

namespace App\Http\Controllers;

use App\BO\PaymentState\Pay\PayFactory;
use App\BO\PaymentState\PaymentState;
use App\BO\Wechat\WechatOperationProxy;
use App\Entities\PaymentEntity;
use App\Utils\EnvUtil;
use App\VO\WechantPayment\MetaInfo\PayInfoFactory;
use App\VO\WechantPayment\PayVO;

/**
 * 微信支付接口
 * Class WechatPaymentController
 * @package App\Http\Controllers
 */
class WechatPaymentController extends BaseController
{
    /**
     * @api {get} /wechat/payment/{tradeNo} 用户支付
     * @apiGroup WechatPayment
     */
    /**
     * 支付
     * @param string $tradeNo
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function pay(string $tradeNo)
    {
        $paymentEntity = PaymentEntity::findByTradeNo($tradeNo);
        if (is_null($paymentEntity)) {
            return $this->showJsonResult(500, '交易不存在');
        }

        $paymentState = new PaymentState($paymentEntity);
        if (!$paymentState->isWaitingPay()) {
            return $this->showJsonResult(500, '状态不正确');
        }

        if ($this->isMockPay($paymentEntity)) {
            // 模拟支付信息
            $paymentState->pay(PayFactory::getMockPayInfo($paymentEntity));
            return $this->successJsonResult();
        }

        $result = WechatOperationProxy::pay(
            $this->getUserEntity()->getOpenid(),
            $paymentEntity->getTradeNo(),
            $paymentEntity->getAmount()
        );

        $payVO = new PayVO();
        $payVO->setPay(PayInfoFactory::getPayInfo($result));

        return $this->successJsonResult($payVO);
    }

    /**
     * @param PaymentEntity $paymentEntity
     * @return bool
     */
    private function isMockPay(PaymentEntity $paymentEntity)
    {
        return EnvUtil::isLocal()   // 本地环境
            || EnvUtil::isTest()    // 测试环境
            || ($paymentEntity->getAmount() == 0);  // 支付金额为 0
    }
}
